import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { NzCascaderOption } from 'ng-zorro-antd/cascader';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzFormatEmitEvent, NzTreeNode, NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { map, tap } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd/message';

export interface TreeNodeInterface {
  key: string;
  name: string;
  shortName?: number;
  level?: number;
  expand?: boolean;
  address?: string;
  children?: TreeNodeInterface[];
  parent?: TreeNodeInterface;
}

interface ProAccountSettingsCity {
  name: string;
  id: string;
  provinceCode: string;
  cityCode: string;
  areaCode: string;
}

@Component({
  selector: 'app-organ-company',
  templateUrl: './company.component.html',
})
export class OrganCompanyComponent implements OnInit {
  form: FormGroup;

  loading: false;
  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private modalSrv: NzModalService,
    private fb: FormBuilder,
    private msg: NzMessageService,
  ) {
    this.form = this.fb.group({
      companyName: [null, [Validators.required]],
      companyShortName: [null, [Validators.required]],
      provinceCode: [null, []],
      cityCode: [null, []],
      areaCode: [null, []],
      parentId: [null, []],
      standard: [null, []],
      companyAddress: [null, []],
    });
  }

  provinces: ProAccountSettingsCity[] = [];
  cities: ProAccountSettingsCity[] = [];
  zoons: ProAccountSettingsCity[] = [];

  listOfMapData: TreeNodeInterface[] = [];
  mapOfExpandedData: { [key: string]: TreeNodeInterface[] } = {};
  expandKeys = ['0-0'];
  value?: string;
  nodeCampan = [];
  company = [];

  values: string[] | null = null;
  companyName: string;
  companyShortName: string;
  provinceCode: string;
  areaCode: string;
  cityCode: string;
  companyAddress: string;
  standard: string;
  searchKey: string;
  ngOnInit(): void {
    // 获取城市
    this.http
      .post('api/getProvinceList', {
        pageNo: '1',
        pageSize: '50',
      })
      .subscribe((res) => {
        this.provinces = res.data.list;
      });

    // 获取企业列表

    this.http.post('api/organ/getCompanyList').subscribe((res) => {
      res.data.forEach((item) => {
        this.nodeCampan.push(
          new NzTreeNode({
            title: item.organName,
            key: item.id,
            children: [],
          }),
        );
      });
      this.company = this.nodeCampan;
    });

    this.getData();

    //
    // this.listOfMapData.forEach((item) => {
    //   this.mapOfExpandedData[item.key] = this.convertTreeToList(item);
    // });
  }

  collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void {
    if (!$event) {
      if (data.children) {
        data.children.forEach((d) => {
          const target = array.find((a) => a.key === d.key)!;
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root: TreeNodeInterface): TreeNodeInterface[] {
    const stack: TreeNodeInterface[] = [];
    const array: TreeNodeInterface[] = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: false });

    while (stack.length !== 0) {
      const node = stack.pop()!;
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level! + 1, expand: false, parent: node });
        }
      }
    }

    return array;
  }

  visitNode(node: TreeNodeInterface, hashMap: { [key: string]: boolean }, array: TreeNodeInterface[]): void {
    if (!hashMap[node.key]) {
      hashMap[node.key] = true;
      array.push(node);
    }
  }

  getData(): void {
    const params = {
      companyName: this.searchKey,
    };
    this.http.post('api/organ/getCompanyTreeList', params).subscribe((res) => {
      this.listOfMapData = res.data;
      this.listOfMapData.forEach((item) => {
        this.mapOfExpandedData[item.key] = this.convertTreeToList(item);
      });
    });
  }

  add(tpl: TemplateRef<{}>): void {
    this.modalSrv.create({
      nzTitle: '新建公司',
      nzContent: tpl,
      nzWidth: 1100,
      nzOnOk: () => {
        // this.loading = true;

        const params = {
          organName: this.form.controls.companyName.value,
          organShortName: this.form.controls.companyShortName.value,
          provinceCode: this.form.controls.provinceCode.value,
          cityCode: this.form.controls.cityCode.value,
          areaCode: this.form.controls.areaCode.value,
          parentId: this.form.controls.parentId.value,
          standard: this.form.controls.standard.value,
          companyAddress: this.form.controls.companyAddress.value,
        };

        this.http.post('api/organ/insertCompany', params).subscribe((res) => {
          if (res.code === 200) {
            this.msg.success('操作成功');
            this.getData();
          }
        });
      },
    });
  }

  loadNode(key: string): Promise<NzTreeNodeOptions[]> {
    return new Promise((resolve) => {
      this.http
        .post('api/organ/getCompanyListByParentId', {
          parentId: key,
          orgType: 1,
        })
        .subscribe((res) => {
          const nodeArray = new Array();
          res.data.forEach((item) => {
            nodeArray.push(
              new NzTreeNode({
                title: item.organName,
                key: item.id,
                children: [],
              }),
            );
          });
          resolve(nodeArray);
        });
    });
  }

  onExpandChange(e: NzFormatEmitEvent): void {
    const node = e.node;
    if (node && node.getChildren().length === 0 && node.isExpanded) {
      this.loadNode(node.key).then((data) => {
        node.addChildren(data);
      });
    }
  }

  choProvince(provinceCod: string): void {
    if (provinceCod !== undefined) {
      // 获取城市
      this.http
        .post('api/getCityList', {
          provinceCode: provinceCod,
        })
        .subscribe((res) => {
          this.cities = res.data;
        });
    }
  }

  choCity(cityCode: string): void {
    if (cityCode !== undefined) {
      // 获取区县
      this.http
        .post('api/getAreaList', {
          cityCode,
        })
        .subscribe((res) => {
          this.zoons = res.data;
        });
    }
  }

  edit(id: string, tpl: TemplateRef<{}>): void {
    const params = {
      id: id,
    };
    this.http.post('api/organ/getCompanyInfoById', params).subscribe((res) => {
      if (res.code === 200) {
        this.companyName = res.data.companyName;
        this.companyShortName = res.data.companyShortName;
        this.provinceCode = res.data.provinceCode;

        this.cityCode = res.data.cityCode;

        this.areaCode = res.data.areaCode;

        this.companyAddress = res.data.companyAddress;
        this.value = res.data.parentId;
        this.standard = res.data.companyRemark;

        // 获取城市
        this.modalSrv.create({
          nzTitle: '修改公司',
          nzContent: tpl,
          nzWidth: 1100,
          nzOnOk: () => {
            const params = {
              companyName: this.form.controls.companyName.value,
              companyShortName: this.form.controls.companyShortName.value,
              provinceCode: this.form.controls.provinceCode.value,
              cityCode: this.form.controls.cityCode.value,
              areaCode: this.form.controls.areaCode.value,
              parentId: this.form.controls.parentId.value,
              standard: this.form.controls.standard.value,
              companyAddress: this.form.controls.companyAddress.value,
              id: res.data.id,
            };

            this.http.post('api/organ/updateCompany', params).subscribe((res) => {
              if (res.code === 200) {
                this.msg.success('修改成功');
                this.getData();
              }
            });
          },
        });
      }
    });
  }

  choArea($event: any) {
    console.log('----------------');
  }

  search(): void {
    this.getData();
  }
}
